import { Suspense } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Receipt, Building2, FileSpreadsheet } from 'lucide-react';
import { formatMoney, calculateProgress } from '@/lib/utils';
import { prisma } from '@/lib/prisma';

const statusMap = {
  active: '进行中',
  completed: '已完工',
  paused: '已暂停'
} as const;

async function SiteExpenseStats() {
  const sites = await prisma.site.findMany({
    include: {
      expenses: {
        select: {
          amount: true,
          type: true,
          paymentDate: true,
        },
      },
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  // 计算每个工地的支出统计
  const siteStats = sites.map(site => {
    const expensesByType = site.expenses.reduce((acc, expense) => {
      acc[expense.type] = (acc[expense.type] || 0) + expense.amount;
      return acc;
    }, {} as Record<string, number>);

    const totalExpenses = Object.values(expensesByType).reduce((a, b) => a + b, 0);
    const remainingBudget = site.contractAmount - totalExpenses;
    const progress = calculateProgress(totalExpenses, site.contractAmount);

    return {
      ...site,
      expensesByType,
      totalExpenses,
      remainingBudget,
      progress,
    };
  });

  // 计算总计
  const totals = siteStats.reduce(
    (acc, site) => {
      acc.contractAmount += site.contractAmount;
      acc.totalExpenses += site.totalExpenses;
      acc.remainingBudget += site.remainingBudget;
      Object.entries(site.expensesByType).forEach(([type, amount]) => {
        acc.expensesByType[type] = (acc.expensesByType[type] || 0) + amount;
      });
      return acc;
    },
    {
      contractAmount: 0,
      totalExpenses: 0,
      remainingBudget: 0,
      expensesByType: {} as Record<string, number>,
    }
  );

  return (
    <div className="space-y-6">
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总合同金额</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totals.contractAmount)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总支出金额</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totals.totalExpenses)}</div>
            <div className="mt-2 h-2 w-full rounded-full bg-secondary">
              <div
                className="h-2 rounded-full bg-primary"
                style={{ width: `${calculateProgress(totals.totalExpenses, totals.contractAmount)}%` }}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总剩余预算</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totals.remainingBudget)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">工地数量</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{sites.length}</div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>工地支出明细</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>工地名称</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">合同金额</TableHead>
                  <TableHead className="text-right">已支出</TableHead>
                  <TableHead className="text-right">材料费</TableHead>
                  <TableHead className="text-right">人工费</TableHead>
                  <TableHead className="text-right">设备费</TableHead>
                  <TableHead className="text-right">其他费用</TableHead>
                  <TableHead className="text-right">剩余预算</TableHead>
                  <TableHead className="text-right">进度</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {siteStats.map((site) => (
                  <TableRow key={site.id}>
                    <TableCell>
                      <Link
                        href={`/sites/${site.id}`}
                        className="font-medium hover:underline"
                      >
                        {site.name}
                      </Link>
                    </TableCell>
                    <TableCell>{statusMap[site.status]}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.contractAmount)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.totalExpenses)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.expensesByType.material || 0)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.expensesByType.labor || 0)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.expensesByType.equipment || 0)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.expensesByType.other || 0)}</TableCell>
                    <TableCell className="text-right">{formatMoney(site.remainingBudget)}</TableCell>
                    <TableCell className="text-right">{site.progress}%</TableCell>
                  </TableRow>
                ))}
                <TableRow className="font-bold">
                  <TableCell>总计</TableCell>
                  <TableCell></TableCell>
                  <TableCell className="text-right">{formatMoney(totals.contractAmount)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.totalExpenses)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.expensesByType.material || 0)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.expensesByType.labor || 0)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.expensesByType.equipment || 0)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.expensesByType.other || 0)}</TableCell>
                  <TableCell className="text-right">{formatMoney(totals.remainingBudget)}</TableCell>
                  <TableCell className="text-right">
                    {calculateProgress(totals.totalExpenses, totals.contractAmount)}%
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export default function ReportsPage() {
  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold tracking-tight">财务报表</h1>
        <Button>
          <FileSpreadsheet className="mr-2 h-4 w-4" />
          导出报表
        </Button>
      </div>

      <Suspense fallback={<div>加载中...</div>}>
        <SiteExpenseStats />
      </Suspense>
    </main>
  );
} 